package com.milepost.workflow.flowinst.ctrl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.milepost.workflow.common.dto.BootstrapTableVoDto;
import com.milepost.workflow.common.enums.DsKeyEnum;
import com.milepost.workflow.common.vo.BootstrapTableVo;
import com.milepost.workflow.config.dynamicDs.DataSourceContextHolder;
import com.milepost.workflow.flowinst.dto.StartFlowDto;
import com.milepost.workflow.flowinst.entity.FlowInstEntity;
import com.milepost.workflow.flowinst.service.FlowInstService;
import com.milepost.workflow.flowinst.vo.FlowInstVo;
import com.milepost.workflow.flowinsttask.entity.FlowInstTaskEntity;
import com.milepost.workflow.flowinsttaskapp.entity.FlowInstTaskAppEntity;
import com.milepost.workflow.response.Response;
import com.milepost.workflow.response.ResponseHelper;
import com.milepost.workflow.response.ReturnCode;
import com.milepost.workflow.user.entity.UsersEntity;
import com.milepost.workflow.user.service.UserService;
import com.milepost.workflow.util.SessionUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author huarf
 * @Description
 * @create 2022-03-27 16:49
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/flowInst")
public class FlowInstCtrl {

    private final FlowInstService flowInstService;

    private final UserService userService;

    /**
     * 查看审批进度
     *
     * @param id
     * @return
     */
    @GetMapping("/getById")
    public Response<FlowInstVo> getById(String id) {

        Response<FlowInstVo> response = null;

        try {
            FlowInstVo flowInstVo = flowInstService.getFlowInstById(id);
            if (flowInstVo != null) {
                // 填充用户名称
                DataSourceContextHolder.setDataSource(DsKeyEnum.USER.getKey());
                UsersEntity userEntity = userService.getById(flowInstVo.getFlowInstEntity().getStartUser());
                if (userEntity != null) {
                    flowInstVo.getFlowInstEntity().setStartUserName(userEntity.getName());
                }

                List<FlowInstTaskEntity> flowInstTaskEntityList = flowInstVo.getFlowInstTaskEntityList();
                for (FlowInstTaskEntity flowInstTaskEntity : flowInstTaskEntityList) {
                    String assignees = flowInstTaskEntity.getAssignees();
                    if (StringUtils.isNoneBlank(assignees)) {
                        String assigneesName = userService.getUserNamesByIds(assignees);
                        flowInstTaskEntity.setAssigneesName(assigneesName);
                    }

                    List<FlowInstTaskAppEntity> flowInstTaskAppEntityList = flowInstTaskEntity.getFlowInstTaskAppEntityList();
                    for (FlowInstTaskAppEntity flowInstTaskAppEntity : flowInstTaskAppEntityList) {
                        UsersEntity userEntityAssignee = userService.getById(flowInstTaskAppEntity.getAssignee());
                        flowInstTaskAppEntity.setAssigneeName(userEntityAssignee.getName());
                    }
                }

                response = ResponseHelper.createSuccessResponse(flowInstVo);
            } else {
                response = ResponseHelper.createResponse(ReturnCode.FAIL, "查看审批进度失败");
            }
        } catch (Exception e) {
            log.error("查看审批进度异常", e);
            response = ResponseHelper.createExceptionResponse(e);
        } finally {
            DataSourceContextHolder.clearDataSource();
        }

        return response;
    }

    /**
     * 查询我的申请
     * @param bootstrapTableVoDto
     * @param flowInstEntity
     * @return
     */
    @GetMapping("/getStartFlowInstList")
    public Response<BootstrapTableVo<FlowInstEntity>> getStartFlowInstList(BootstrapTableVoDto bootstrapTableVoDto, FlowInstEntity flowInstEntity, HttpSession session) {

        Response<BootstrapTableVo<FlowInstEntity>> response = null;

        try {
            flowInstEntity.setStartUser(SessionUtil.getCurrUser(session).getId());
            Page<FlowInstEntity> flowInstEntityPage = flowInstService.getStartFlowInstList(bootstrapTableVoDto, flowInstEntity);

            // 填充用户名称
            DataSourceContextHolder.setDataSource(DsKeyEnum.USER.getKey());
            for (FlowInstEntity record : flowInstEntityPage.getRecords()) {
                if (StringUtils.isNoneBlank(record.getStartUser())) {
                    UsersEntity userEntity = userService.getById(record.getStartUser());
                    if (userEntity != null) {
                        record.setStartUserName(userEntity.getName());
                    }
                }
            }

            BootstrapTableVo<FlowInstEntity> bootstrapTableVo = new BootstrapTableVo<>(flowInstEntityPage);
            response = ResponseHelper.createSuccessResponse(bootstrapTableVo);
        } catch (Exception e) {
            log.error("查询我的申请列表异常", e);
            response = ResponseHelper.createExceptionResponse(e);
        } finally {
            DataSourceContextHolder.clearDataSource();
        }

        return response;
    }

    /**
     * 发起流程
     * @param startFlowDto
     * @return
     */
    @PostMapping("/startFlow")
    public Response<String> startFlow(@RequestBody StartFlowDto startFlowDto, HttpSession session) {

        Response<String> response = null;

        try {
            startFlowDto.setStartUser(SessionUtil.getCurrUser(session).getId());
            // 发起流程
            String flowInstId = flowInstService.startFlow(startFlowDto);
            if (flowInstId != null) {
                response = ResponseHelper.createSuccessResponse(flowInstId);
                response.setMsg("发起流程成功");
            } else {
                response = ResponseHelper.createResponse(ReturnCode.FAIL, "发起流程失败");
            }

        } catch (Exception e) {
            log.error("发起流程异常", e);
            response = ResponseHelper.createExceptionResponse(e);
        }

        return response;
    }

}
